package com.imu.upload.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {
    @GetMapping("/test")
    public String test(){
        System.out.println("test....");
        return "notlogining";
    }

    @Value("${file.upload-base-path}")
    private String path;

    @PostMapping
    public String upload(MultipartFile[] files){
        log.info("多文件上传");

        List<String> originalFilenames = new ArrayList<>();
        for (MultipartFile file : files) {
            if (!file.isEmpty()){

                //           获取原始文件名称
                String originalFilename = file.getOriginalFilename();
                originalFilenames.add(originalFilename);
            }
        }
//
        List<String> suffixs = new ArrayList<>();
//        获取后缀
        for (String originalFilename : originalFilenames) {
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            suffixs.add(suffix);
        }

        List<String> filenames = new ArrayList<>();
        for (String suffix : suffixs) {
            //        使用UUID随机生成文件名
            String filename = UUID.randomUUID().toString()+suffix;
            filenames.add(filename);
        }

//      判断当前目录是否存在，不存在则创建
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }

//        转存
        try {
            for (int i = 0; i < files.length; i++) {
                if (!files[i].isEmpty()){
                    files[i].transferTo(new File(path+ filenames.get(i)));
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

}
